#!/bin/bash

function startOrRestartService()
{
	domain=$1
	service=$2
	if [[ $domain == system* ]]; then
		plistPath="/Library/LaunchDaemons"
	elif [[ $domain == gui/* ]]; then
		plistPath="/Library/LaunchAgents"
	fi
	startCmd="/bin/launchctl bootstrap $domain $plistPath/$service.plist"
	restartCmd="/bin/launchctl kickstart -k $domain/$service"
	isLoaded=`/bin/launchctl print $domain/$service | wc -l`
	if [ $isLoaded -gt "0" ]; then
		echo "Restarting Service: '$restartCmd'"
		eval $restartCmd || exit 1
	else
		echo "Starting Service: '$startCmd'"
		eval $startCmd || exit 1
	fi
}

# Load Launch Agents in all active User sessions
# There will be one loginwindow instance for each logged in user, 
# get its uid (this will correspond to the logged in user's id.) 
# Then use launchctl bootstrap gui/uid to auto load the Service 
# for each user.
declare -a launchAgents=(
    "org.scalar.usernotification"
    "org.scalar.service"
)
for uid in $(ps -Ac -o uid,command | grep -iw "Finder" | awk '{print $1}'); do
    for nextLaunchAgent in "${launchAgents[@]}"; do
        startOrRestartService "gui/$uid" $nextLaunchAgent
    done
done 
